<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Shop extends MY_Controller {

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Default function
     */
    public function index($id = false,$alias=false,$post_id=false,$user_id=false,$page=false)
    {
        
        if(!$id || !$alias) show_404();
        
        $this->load->model('categories');
        $category = $this->categories->getCat(array('cat_id'=>$id));
        
        $catname = $this->_global->_unserialize($category->cat_name);
        $catdesc = $this->_global->_unserialize($category->cat_desc);
        if(!$post_id){
            $a =$this->_global->_unserialize($category->cat_alias); 
        if($a[$this->session->userdata('lan')]['alias']!=$alias) show_404();
            $this->load->library('pagination');
            $config['base_url'] = base_url().$alias.'-'.$id.'-page-'; 
            $posts = _get_product($id);
            $config['total_rows'] = count($posts);
            $config['per_page'] = 24;
            $this->pagination->initialize($config);
            $this->assign('pages',$this->pagination->create_links());
            
        }else{
            
            $this->load->model('rates');
            $posts = _get_detail_product($post_id);
            
            $a = $this->_global->_unserialize($posts->product_alias);
            if($a[$this->session->userdata('lan')]['alias']!=$alias) show_404();
            $rate = $this->rates->get_rate($posts->product_id);
            if(!empty($rate)){
            $rate = ceil($rate[0]->point/$rate[0]->click);
            }else
            $rate=0;
            $this->assign('rate',$rate);
           // $this->assign('recapcha',$this->_create_recaptcha());
            
        }
        if($user_id){
            $this->session->set_userdata('ctv',$user_id);
            redirect('shop/c'.$id.'/'.$alias.'-'.$post_id);
            
        }
        
        $this->assign('posts',$posts);
        $this->assign('cat_name',$catname[$this->session->userdata('lan')]['title']);
        $this->assign('cat_desc',$catdesc[$this->session->userdata('lan')]['cat_desc']);
        $this->assign('cat_id',$id); 
        $this->assign('post_id',$post_id);
        $this->assign('alias',$alias); 
    }
    
    
    public function getCart(){
        $this->load->library('cart');
        $this->load->library('nganluong');
        global $site_info;
        $items = $this->cart->contents();
        $this->assign('items',$this->cart->contents());
        $return_url = base_url().'index/shop/complete';
        $price = $this->cart->total();
        $order_code = "1234567";
        $transaction_info ='Ðon hàng c?a b?n t?i Boogiegoogie:';
        foreach($items as $item){
            $transaction_info.='<p>'.$item['name'].' màu s?c:'.$item['options']['Color'].' kích thu?c'.$item['options']['Size'].'</p>';
        }
        $receiver = $site_info['receiver_email'];
        $url = $this->nganluong->buildCheckoutUrl($return_url, $receiver, $transaction_info, $order_code, $price);
        $this->assign('checkout_button',$url);
       // $this->cart->destroy();
    }
    public function infoCart(){
        $this->load->library('cart');
        if(!is_array($this->cart->contents())){
            redirect();
        }
    }
    
    public function get_country($parent_id=0){
        $this->disable_view();
        echo _get_country3($parent_id);
    }
    public function checkout(){
        $this->disable_view();
         $this->load->library('cart');
        $post = $this->input->post(null,true);
        $this->load->model('orders');
        if($post['rc'] == 1){
            $shipping_city_id = $post['city'];
            $shipping_ward_id = $post['ward'];
        }else
        {
            $shipping_city_id = $post['rc_city'];
            $shipping_ward_id = $post['rc_ward'];
        }
        $fields = array(
            'user_id' => $this->session->userdata('ctv')
            ,'created_at'       => time()
            ,'user_ip'          => ip2long($_SERVER['REMOTE_ADDR'])
            ,'currency_code'    =>'vnd'
            ,'shipping_method'  =>$post['opt_transaction']
            ,'order_comment'    =>$post['more']
            ,'payment_method'   =>$post['opt_payment']
            ,'promotion_code'   =>$post['promotion_code']
            ,'order_address'    =>$post['address']
            ,'order_city_id'    =>$post['city']
            ,'order_ward_id'    =>$post['ward']
            ,'order_email'      =>$post['email']
            ,'order_fullname'   =>$post['fullname']
            ,'shipping_fullname'=>$post['rc_fullname']
            ,'shipping_address' =>$post['rc_address']
            ,'shipping_city_id' =>$shipping_city_id
            ,'shipping_ward_id' =>$shipping_ward_id
            ,'shipping_telephone'=>$post['rc_tel']
            ,'shipping_email'   =>$post['rc_email']
            ,'order_telephone'  => $post['tel']
            ,'delivery_date'    =>$post['hour'].'-'.$post['min'].' '.$post['date'].'/'.$post['month'].'/'.$post['year']
            ,'order_details'     =>$this->_global->_serialize($this->cart->contents())
        );
        $this->orders->addOder($fields);
    }
    
    public function complete(){
        $this->disable_view();
        echo "Success";
    }
    public function addToCart(){
        $this->disable_view();
        $this->load->library('cart');
        $post = $this->input->post(null,true);
        $data = array(
               'id'      => $post['product_id'],
               'qty'     => $post['qty'],
               'price'   => $post['price'],
               'name'   => $post['c_name'],
               'options' => array('Size' => $post['_size'],'link'=>$post['link'], 'Color' => $post['colors'])
            );
            $this->cart->insert($data);
            $this->output->set_output($this->cart->total_items());
    }
    
    public function comment($act=false,$product_id){
        if(!$act) return false;
        $this->disable_view();
        $this->load->model('comment');
        $time =time();
        if(_check_recaptcha()){
       $rs =$this->comment->addComment(array('fullname' =>strip_tags($this->input->post('name',true))
                                        ,'email'    =>strip_tags($this->input->post('email',true))
                                        ,'comment'  =>strip_tags($this->input->post('content',true))
                                        ,'created'  =>$time
                                        ,'object_id'=>$product_id
                                        ,'comment_type'=>'shop'));
        if($rs>0) $this->output->set_output($time);
        }else
        {
            $this->output->set_output(0);
        }
    }
    public function loadComment($obj_id,$time){
        $this->disable_view();
        $sql="select * from comments where object_id = '".$obj_id."' order by comment_id desc";
        $query = $this->db->query($sql);
        if($query->num_rows()>0)
        {
            $str='';
            $rs = $query->result();
            foreach($rs as $comment){
                $str.='<p style="padding:2px;border-bottom:1px solid #ccc"><b><a href="mailto:'.strip_tags($comment->email).'">'.strip_tags($comment->fullname).'</b></a> : '.strip_tags($comment->comment).'</p>';
            }
        }
        $this->output->set_output($str);
    }
    public function tags($type,$tag){
        $posts = _search_tags($type,$tag);
        $this->assign('posts',$posts);
    }
    public function rate($id,$point){
        $this->disable_view();
        $this->load->model('rates');
        $rate = $this->rates->get_rate($id);
        if(count($rate)>0){
            $click = $rate[0]->click + 1;
            $point = $rate[0]->point + $point;            
            $r = $this->rates->update_rate(array('click'=>$click,'point'=>$point),$rate[0]->rate_id);
            $this->output->set_output($r);
            
        }else
        {
            $r = $this->rates->add_rate(array('product_id'=>$id,'point'=>$point,'click'=>1));
            $this->output->set_output($r);
        }
        //$this->rates->add_rate(array(''))
    }
    
    public function addwishlist($product_id){
        if(!$product_id) show_404();
        $this->disable_view();
        $this->load->model('wishlist');
        $data = array('product_id'=>$product_id
                    ,'user_id'=>$this->tank_auth->get_user_id()
                    );
        if($this->wishlist->addWishlist($data)>0) redirect('account');
    }
    
    
}